#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <math.h>

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    QPushButton* button = nullptr;

    switch(event->key()) {
    case Qt::Key_0: button = ui->btnNum0; break;
    case Qt::Key_1: button = ui->btnNum1; break;
    case Qt::Key_2: button = ui->btnNum2; break;
    case Qt::Key_3: button = ui->btnNum3; break;
    case Qt::Key_4: button = ui->btnNum4; break;
    case Qt::Key_5: button = ui->btnNum5; break;
    case Qt::Key_6: button = ui->btnNum6; break;
    case Qt::Key_7: button = ui->btnNum7; break;
    case Qt::Key_8: button = ui->btnNum8; break;
    case Qt::Key_9: button = ui->btnNum9; break;
    case Qt::Key_Plus: button = ui->btnPlus; break;
    case Qt::Key_Minus: button = ui->btnMinus; break;
    case Qt::Key_Asterisk: button = ui->btnMultiple; break;
    case Qt::Key_Slash: button = ui->btnDivide; break;
    case Qt::Key_Period:
    case Qt::Key_Comma: button = ui->btnPoint; break;
    case Qt::Key_Equal:
    case Qt::Key_Enter:
    case Qt::Key_Return: button = ui->btnEquals; break;
    case Qt::Key_Backspace: button = ui->btnDelete; break;
    case Qt::Key_Escape:
    case Qt::Key_C:
        if (event->modifiers() == Qt::NoModifier) {
            button = ui->btnC;
        }
        break;
    case Qt::Key_Percent: button = ui->btnPercent; break;
    }

    if (button) {
        button->click();
        event->accept();
    } else {
        QMainWindow::keyPressEvent(event);
    }
}
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->btnNum0,SIGNAL(clicked()),this,SLOT(btnNumClicked()));
    connect(ui->btnNum1,SIGNAL(clicked()),this,SLOT(btnNumClicked()));
    connect(ui->btnNum2,SIGNAL(clicked()),this,SLOT(btnNumClicked()));
    connect(ui->btnNum3,SIGNAL(clicked()),this,SLOT(btnNumClicked()));
    connect(ui->btnNum4,SIGNAL(clicked()),this,SLOT(btnNumClicked()));
    connect(ui->btnNum5,SIGNAL(clicked()),this,SLOT(btnNumClicked()));
    connect(ui->btnNum6,SIGNAL(clicked()),this,SLOT(btnNumClicked()));
    connect(ui->btnNum7,SIGNAL(clicked()),this,SLOT(btnNumClicked()));
    connect(ui->btnNum8,SIGNAL(clicked()),this,SLOT(btnNumClicked()));
    connect(ui->btnNum9,SIGNAL(clicked()),this,SLOT(btnNumClicked()));

    connect(ui->btnDivide,SIGNAL(clicked()),this,SLOT(btnBinaryOperatorClicked()));
    connect(ui->btnMultiple,SIGNAL(clicked()),this,SLOT(btnBinaryOperatorClicked()));
    connect(ui->btnMinus,SIGNAL(clicked()),this,SLOT(btnBinaryOperatorClicked()));
    connect(ui->btnPlus,SIGNAL(clicked()),this,SLOT(btnBinaryOperatorClicked()));

    connect(ui->btnPercent,SIGNAL(clicked()),this,SLOT(btnUnaryOperatorClicked()));
    connect(ui->btnSqrt,SIGNAL(clicked()),this,SLOT(btnUnaryOperatorClicked()));
    connect(ui->btnSquare,SIGNAL(clicked()),this,SLOT(btnUnaryOperatorClicked()));
    connect(ui->btnInverse,SIGNAL(clicked()),this,SLOT(btnUnaryOperatorClicked()));
    connect(ui->btnSign,SIGNAL(clicked()),this,SLOT(btnUnaryOperatorClicked()));

    ui->btnEquals->setStyleSheet("background-color: rgb(124, 176, 255);");

    ui->btnDivide->setStyleSheet("background-color: rgb(225, 225, 225);");
    ui->btnMultiple->setStyleSheet("background-color: rgb(225, 225, 225);");
    ui->btnMinus->setStyleSheet("background-color: rgb(225, 225, 225);");
    ui->btnPlus->setStyleSheet("background-color: rgb(225, 225, 225);");
    ui->btnSqrt->setStyleSheet("background-color: rgb(225, 225, 225);");
    ui->btnSquare->setStyleSheet("background-color: rgb(225, 225, 225);");
    ui->btnInverse->setStyleSheet("background-color: rgb(225, 225, 225);");

    ui->btnPercent->setStyleSheet("background-color: rgb(235, 235, 235);");
    ui->btnC->setStyleSheet("background-color: rgb(235, 235, 235);");
    ui->btnCE->setStyleSheet("background-color: rgb(235, 235, 235);");
    ui->btnDelete->setStyleSheet("background-color: rgb(235, 235, 235);");


}

MainWindow::~MainWindow()
{
    delete ui;
}

QString MainWindow::calculation(bool clearContainers)
{
    if(operands.size() >= 2 && opcodes.size() >= 1) {
        double operand1 = operands[0].toDouble();
        double operand2 = operands[1].toDouble();
        QString op = opcodes[0];

        double result = 0;
        if(op == "+") {
            result = operand1 + operand2;
        } else if(op == "-") {
            result = operand1 - operand2;
        } else if(op == "×") {
            result = operand1 * operand2;
        } else if(op == "÷") {
            if(operand2 == 0) return "Error";
            result = operand1 / operand2;
        }

        if(clearContainers) {
            operands.clear();
            opcodes.clear();
        } else {
            // 只移除已计算的部分
            operands.removeFirst();
            operands.removeFirst();
            opcodes.removeFirst();
        }

        return QString::number(result);
    }
    return "0";
}

void MainWindow::btnNumClicked()
{
    QString digit = qobject_cast<QPushButton *>(sender())->text();

    if(operand == "0" && digit != "0")
        operand = "";
    operand += digit;
    ui->display->setText(operand);
}

void MainWindow::on_btnPoint_clicked()
{
    if(!operand.contains(".")) {
        if(operand.isEmpty()) {
            operand = "0";
        }
        operand += ".";
        ui->display->setText(operand);
    }
}

void MainWindow::on_btnDelete_clicked()
{
    if(!operand.isEmpty()) {
        operand = operand.left(operand.length()-1);
        ui->display->setText(operand.isEmpty() ? "0" : operand);
    }
}

void MainWindow::btnUnaryOperatorClicked()
{
    if(!operand.isEmpty()){
        double result = operand.toDouble();
        QString op = qobject_cast<QPushButton*>(sender())->text();

        if(op == "%"){
            result /= 100.0;
        } else if(op == "1/x") {
            if(result == 0) {
                ui->display->setText("Error");
                return;
            }
            result = 1 / result;
        } else if(op == "x^2") {
            result *= result;
        } else if(op == "√x") {
            if(result < 0) {
                ui->display->setText("Error");
                return;
            }
            result = sqrt(result);
        } else if(op == "±") {
            result = -result;
        }

        operand = QString::number(result);
        ui->display->setText(operand);
    }
}

void MainWindow::on_btnC_clicked()
{
    operand.clear();
    operands.clear();
    opcodes.clear();
    ui->display->setText("0");
}

void MainWindow::on_btnCE_clicked()
{
    operand.clear();
    ui->display->setText("0");
}

void MainWindow::btnBinaryOperatorClicked()
{
    QString opcode = qobject_cast<QPushButton*>(sender())->text();
    // 如果当前有输入的数字
    if(!operand.isEmpty()) {
        // 如果已经有待计算的操作，先计算
        if(operands.size() == 1 && opcodes.size() == 1) {
            operands.push_back(operand);
            QString result = calculation(false); // 计算但不完全清空
            ui->display->setText(result);
            // 将计算结果作为新的第一个操作数
            operands.clear();
            opcodes.clear();
            operands.push_back(result);
            opcodes.push_back(opcode);
        } else {
            // 第一次输入或只有结果值
            operands.push_back(operand);
            opcodes.push_back(opcode);
        }
        operand.clear();
    }
    // 如果没有新输入的数字，但显示区域有数字（之前的结果）
    else if(ui->display->text() != "0" && ui->display->text() != "Error") {
        // 使用显示的数字作为第一个操作数
        QString displayText = ui->display->text();
        if(operands.isEmpty()) {
            operands.push_back(displayText);
            opcodes.push_back(opcode);
        } else if(operands.size() == 1 && opcodes.size() == 1) {
            // 如果已经有操作数，只更新运算符
            opcodes[0] = opcode;
        }
    }

}

void MainWindow::on_btnEquals_clicked()

{
    // 确保有足够的操作数和操作符进行计算
    if(operands.size() == 1 && opcodes.size() == 1) {
        // 如果当前有输入，使用当前输入作为第二个操作数
        if(!operand.isEmpty()) {
            operands.push_back(operand);
        }
        // 如果没有当前输入，使用第一个操作数作为第二个操作数（重复计算）
        else if(operands.size() == 1) {
            operands.push_back(operands.at(0));
        }

        QString result = calculation(true);
        ui->display->setText(result);
        operand = result; // 保存结果以便继续使用
    }
    // 如果没有待计算的操作，但有当前输入，直接显示
    else if(!operand.isEmpty()) {
        // 什么都不做，保持显示当前数字
    }
    else {
        ui->display->setText("0");
    }
}
